/*
 * GeoVISTA Center (Penn State, Dept. of Geography)
 * Copyright (c), 2003-2011,  Jin Chen and Alan M. MacEachren, GeoVISTA Center, Penn State University
 * All Rights Researved.
 *
 * This library is developed and distributed for free usage,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * You can redistribute and/or modify it under the terms of the
 * Simplified BSD License
 *
 *
 *
 *
 *
 *
 *
 *
 * @author: jin Chen
 * @date: Jun 17, 2003
 * @version: $VERSION$
 */
package edu.psu.geovista.app.pcp.plot.control;

import edu.psu.geovista.app.pcp.Pcp;
import edu.psu.geovista.app.pcp.plot.gui.PcpCanvas;
import edu.psu.geovista.app.pcp.toolkits.SplitControl;
import org.jfree.data.time.TimeSeries;

import javax.swing.*;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;

public class PlotSplitControl extends SplitControl{
    ConfigureFrame frm;
    DfConfigManager config;
    JPanel selBar; //selection Bar
    JPanel cp;//config panel
    JFrame popupFrm=new JFrame(); //The popup frame contain configuring and operating sections

    int startLoc=0;//27;
    int dividerCloseSize=1;
    int dividerOpenSize=0;//should be 10.Since we do not want to use left pane anymore, set it to 0.
    protected JScrollPane spRight;

    public PlotSplitControl(JComponent left, JComponent right) {

        this.left =left;
        this.config =(DfConfigManager)this.left ;
        this.right =right;
        cp=new JPanel();

        selBar=createSelBar();//contain "Configure" button
        //cp.setLayout(new BorderLayout());
        //help to allocate space for selbar ->
        JPanel temp=new JPanel();
        temp.setLayout(new BorderLayout());
        JPanel empty=new JPanel();
        empty.setPreferredSize(new Dimension(25,125));
        empty.setBackground(new Color(244,239,239));
        temp.add(selBar);
        temp.setBackground(new Color(244,239,239));
        //<-



        JScrollPane spLeft=new JScrollPane(cp);

        spLeft.setMaximumSize(new Dimension(this.getDividerLocation(),this.getSize().height ));

        //spRight = new AutoScrollablePane(right);
        spRight = new JScrollPane(right);//right is pcpCanvas
        if(right instanceof PcpCanvas){
            PcpCanvas canvas=(PcpCanvas) right;
            canvas.setContainerScrollPane(spRight);
        }
        //VitUtils.setAutoScroll(spRight,right);



        //todo: need add  ContaineeAutoLayoutOnSizeChange between viewPort and lgc which will change size over time


        //
        splitPane=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,false,spLeft,spRight);

        //Configure splitPane GUI
        splitPane.setOneTouchExpandable(true);
        splitPane.setDividerLocation(startLoc);
        splitPane.setDividerSize(dividerCloseSize);
        //splitPane.setLastDividerLocation(0);


        this.setLayout(new BorderLayout());
        this.add(splitPane);
        this.add(temp,BorderLayout.WEST );



    }
    //return the scollpane containing pcpcanvas
    public JScrollPane getSpRight() {
        return spRight;
    }


    protected void setup(){

    }
    private JPanel createSelBar() {
        JPanel sbar=new JPanel();
        sbar.setLayout(new GridLayout(4,1)); //need set (4,1) so that the configure button will be on the top of the bar
        //JButton axis=new JButton("<html>A<br>X<br> I<br>S</html>");
        JButton axis=new JButton("   Configure");//"            Data"
        axis.setVerticalAlignment(SwingConstants.CENTER );
        axis.setHorizontalAlignment(SwingConstants.CENTER );

                    axis.addActionListener(new showAction(){
                            public void actionPerformed(ActionEvent e){
                                if (config==null)return;

                                JFrame myf=getPopupFrm();
                                if(!myf.isVisible() ){
                                    //Note: Default close operation is set to HIDE_ON_CLOSE by default.
                                    DfConfigManager comp= config;//.getConfig() ;
                                    myf.addWindowListener(config);
                                    if(comp!=null)
                                    myf.getContentPane().add(comp);
                                    myf.setBounds(100,100,(int)Math.round(400*1.414),520); // 
                                    //myf.pack() ;//keep the preference size of child component, it makes setBounds ineffective
                                    myf.setVisible(true);
                                }
                                myf.show() ;

                            }
                    });


       //ButtonGroup bgrp=new ButtonGroup();
        makeVerticalButton(axis);

        Color color=new Color(244,239,239);
         axis.setBackground(color);

        axis.setToolTipText("Configure and manipulate plot");//Manipulate data by operating on axis. Such as show range and axes' order") ;
        //data.setToolTipText("Classification and animation on data");
        GridBagConstraints gridBagConstraints;

       //sbar.add(plot);
       sbar.add(axis);

       return sbar;
    }

    public JFrame getPopupFrm() {
        return popupFrm;
    }

    public  static Font getVerticalFont(AbstractButton btn){
        AffineTransform trans = new AffineTransform();
						trans.rotate(-Math.PI/2, btn.getWidth(), btn.getHeight()/2);
						Font font = new Font("", Font.BOLD, 11);
						font = font.deriveFont(trans);
        return font;
    }

    public static AbstractButton makeVerticalButton(AbstractButton btn){
         btn.setFont(getVerticalFont(btn));
         btn.setVerticalAlignment(SwingConstants.BOTTOM );
         btn.setMargin(new Insets(2,8,2,8));
         btn.setBorderPainted(false);
         btn.setAlignmentX(SwingConstants.TOP );
         return btn;

    }
    public abstract class showAction implements ActionListener{
        boolean showed=false;
        //int startLoc=30;

             public void actionPerformed(ActionEvent e){
                  //config.setActiveConfig(BasicConfig.AXIS_CONFIG );
                  this.show() ;

             }

             protected  void show(){
                 splitPane.setDividerLocation(dividerLocation);
                 splitPane.setDividerSize(dividerOpenSize);
                 //todo show frm
                 frm.show() ; // 
                 
             }
             protected void reset(){
                splitPane.setDividerLocation(startLoc);
                 splitPane.setDividerSize(dividerCloseSize);
             }
    }

    public void setConfig(DfConfigManager config) {
        JFrame popupFrm=this.getPopupFrm() ;
        if (this.config !=null){
             popupFrm.removeWindowListener(config);
             popupFrm.getContentPane().remove(this.config) ;// 

            cp.remove(this.config); //MUST, otherwise if you change dataSet(open a new dataSet), AxisConfig's axisNameList won't appear updated
        //cp.removeAll();          ???
        }
        this.config = config;

        //PopupFrame
       Pcp plot=config.getTargetUI().getPlot() ;
        String frameOwner="";

        /*Forts    //todo: no mode any more, need check instance type
        if(pcp.getMode() ==DfPcp.MODE_PCP ){
           frameOwner="PCP";
           //popupFrm.setBackground(Color.yellow );
        }
        else if(pcp.getMode() ==DfPcp.MODE_TIMESERIES ){
            frameOwner="Time Series";
        }*/

       if(plot instanceof TimeSeries){
            frameOwner="Time Series";
       }
       else if (plot instanceof Pcp){
            frameOwner="PCP";
       }
       popupFrm.setTitle(frameOwner+"'s configuration ");

       popupFrm.addWindowListener(config);
       // 
       popupFrm.getContentPane().add(this.config );
       popupFrm.getContentPane().validate() ;

       this.config.setPopupfrm(popupFrm);

    }
    /*******************************************************************************************************
     *                control internalframe
     *******************************************************************************************************/
    private class ConfigureFrame extends JInternalFrame{
        DfConfigManager config;
        public ConfigureFrame(String title, boolean resizable, boolean closable, boolean maximizable, boolean iconifiable) {
            super(title, resizable, closable, maximizable, iconifiable);
        }

        public DfConfigManager getConfig() {
            return config;
        }
        //please only call once
        public void setConfig(DfConfigManager config) {
            this.config = config;
            this.getContentPane().add(config);
        }

    }
    private class InternalFrameControl implements InternalFrameListener,VetoableChangeListener{
        public void internalFrameOpened(InternalFrameEvent e) {
        }

        public void internalFrameClosing(InternalFrameEvent e) {
        }

        public void internalFrameClosed(InternalFrameEvent e) {
        }

        public void internalFrameIconified(InternalFrameEvent e) {
            ConfigureFrame intfrm=(ConfigureFrame) e.getInternalFrame() ;
            JFrame myf=new JFrame();
            DfConfigManager comp= intfrm.getConfig() ;
            if(comp!=null)
            myf.getContentPane().add(comp);
            myf.setBounds(100,100,800,600);
            myf.setVisible(true);
             //close configure page
             closeConfigurePage();

            /*JInternalFrame frm=e.getInternalFrame() ;
        ConfigManager comp= intfrm.getConfig() ;
        Object[] btnOptions = {"Load", "Cancel"};
        JOptionPane.showOptionDialog(frm, comp,"title",JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,null,btnOptions,btnOptions[0]);*/
        }

        public void internalFrameDeiconified(InternalFrameEvent e) {
            // 
            if(frm!=null &&config!=null)
                    frm.setConfig(config);
            frm.revalidate() ;
        }

        public void internalFrameActivated(InternalFrameEvent e) {
        }

        public void internalFrameDeactivated(InternalFrameEvent e) {
        }

        public void vetoableChange(PropertyChangeEvent evt)
                throws PropertyVetoException {
            String name=evt.getPropertyName() ;

            System.out.println("property:"+name);
            if(name.equals(JInternalFrame.IS_CLOSED_PROPERTY ) ){
                System.out.println("throw close cancel!");
                closeConfigurePage();
                throw new PropertyVetoException("close cancel",evt);
            }

        }

        public void closeConfigurePage() {
            splitPane.setDividerLocation(startLoc);
             splitPane.setDividerSize(dividerCloseSize);
        }

    }

}
